package com.taiji.dicom4cloud.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ArrayUtil;
import com.taiji.dicom4cloud.admin.service.SysLoginService;
import com.taiji.dicom4cloud.admin.service.SysUserService;
import com.taiji.dicom4cloud.admin.utils.AesEncryptUtils;
import com.taiji.dicom4cloud.common.core.constrant.constant.SecurityConstants;
import com.taiji.dicom4cloud.common.core.exception.ServiceException;
import com.taiji.dicom4cloud.common.model.dto.UserInfo;
import com.taiji.dicom4cloud.common.model.entity.SysUser;
import com.taiji.dicom4cloud.common.model.vo.UserVO;
import com.taiji.dicom4cloud.common.security.model.CommonUserDetails;
import com.taiji.dicom4cloud.common.security.service.IUserDetailService;
import com.taiji.dicom4cloud.common.security.service.TokenService;
import com.taiji.dicom4cloud.common.security.utils.SecurityUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description
 * @Author fanxl
 * @Date 2021/6/2
 **/
@Service
@AllArgsConstructor
public class SysLoginServiceImpl implements SysLoginService {

    private IUserDetailService iUserDetailService;

    private AuthenticationManager authenticationManager;

    private TokenService tokenService;

    private SysUserService sysUserService;

    @Override
    public UserVO loginByPassword(String username, String password) {
        UserVO userVO  = new UserVO();

        SysUser sysUser = iUserDetailService.getByUsername(username);
        CommonUserDetails userDetails = new CommonUserDetails();
        BeanUtil.copyProperties(sysUser,userDetails);

        try {
            password = AesEncryptUtils.decode(password);

        } catch (Exception e) {
            throw new ServiceException("解密失败");
        }

        Collection<? extends GrantedAuthority> authorities = iUserDetailService.getUserInfo(sysUser);
        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username,password,authorities);
        authenticationManager.authenticate(token);
        BeanUtil.copyProperties(sysUser,userVO);
        userVO.setAccess_token(tokenService.getToken(userDetails));
        userVO.setRefresh_token(userVO.getAccess_token());
        return userVO;
    }

}
